var Develop = {
	server: 'http://baodan.9ok.xin/',
	server_path: 'http://baodan.9ok.xin/',
	server_name: 'http://baodan.9ok.xin/index.php/Api/',
};

var Develop2 = {
	server: 'http://localhost/daikuan/',
	server_path: 'http://localhost/daikuan/',
	server_name: 'http://localhost/daikuan/index.php/Api/',
};

var realVersion = Develop;
var SERVER = realVersion.server;
var SERVER_PATH = realVersion.server_path;
var SERVER_NAME = realVersion.server_name;

var common = null;
$(function(){


	common = {
		
		setLocVal: function(name, value) {
			localStorage[name] = value;
		},
		getLocVal: function(name) {
			var result = localStorage[name];
			if(typeof(result) == "undefined") {
				result = "";
			}
			return result;
		},
		clearLocVal: function(key) {
			if(!key) {
				localStorage.clear();
			} else {
				localStorage.removeItem(key);
			}

		},
		getFileVal: function(chat_id, func, error) {
			plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
				// 可通过fs进行文件操作 
				fs.root.getFile(chat_id + '.json', {
					create: true
				}, function(fileEntry) {
					fileEntry.file(function(file) {
						//alert("getFile:" + JSON.stringify(file));
						var fileReader = new plus.io.FileReader();
						fileReader.readAsText(file, 'utf-8');
						fileReader.onloadend = func; //返回文本数据，空的话 就是 '' 
						//alert(evt.target.result);
						//alert(file.size + '--' + file.name);
					});
				});
			}, error);
		},
		removeHTMLTag: function(str) {
			if(typeof(str) == 'string') {
				str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
				str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
				//str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
				str = str.replace(/&nbsp;/ig, ''); //去掉&nbsp;
				return str;
			} else {
				return '';
			}

		},
		/**
		 * 
		 * @param {Object} chat_id
		 * 
		 */
		setFileVal: function(chat_id, data, func) {
			plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
				fs.root.getFile(chat_id + '.json', {
					create: true
				}, function(fileEntry) {
					fileEntry.file(function(file) {
						console.log("File Size:" + file.size);
						var fileWrite = new plus.io.FileWriter;
						fileEntry.createWriter(function(fileWrite) {
							fileWrite.seek(0);
							fileWrite.write(data);
							fileWrite.onwrite = func;
						})
					});
				});
			});
		},
		delFile: function(chat_id, func) {
			plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
				// 可通过fs进行文件操作 
				fs.root.getFile(chat_id + '.json', {
					create: true
				}, function(fileEntry) {
					fileEntry.remove(func); //删除指定文件
				});
			});
		},
		pushInit: function() {
			var info = plus.push.getClientInfo();
			var params = {
				url: 'mod=System&act=setUserClientId',
				data: {
					clientid: info.clientid,
					os: plus.os.name,
					devicetoken: info.token,
					version: 'student'
				}
			};
			common.JsonPost(params, function(data) {
				console.log(JSON.stringify(data));
			})
			console.log(JSON.stringify(info));
			plus.push.addEventListener("click", function(msg) {
				// 分析msg.payload处理业务逻辑 
				if(plus.os.name == 'iOS') {
					getMsg(msg, 'click');
				}
				plus.push.clear();
			}, false);
			plus.push.addEventListener("receive", function(msg) {
				getMsg(msg, "receive");
			}, false);
			plus.push.clear();
		},
		getLocFile: function(item) {
			var path_arr = item.url.split("data/");
			var path_str = path_arr[1].split("/");
			var path = "/";
			var file_name = '';
			for(var key in path_str) {
				if(key == path_str.length - 1) {
					file_name = path_str[key];
					continue;
				}
				path = path + path_str[key] + "/";
			}
			plus.io.resolveLocalFileSystemURL("_downloads" + path + file_name, function(entry) {
				// 可通过entry对象操作test.html文件 
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					//setTimeout(function(){
					//console.log(item.id);
					document.getElementById(item.id).setAttribute(item.attr, file.fullPath);
					//},300);
				});
			}, function(e) {
				plus.downloader.createDownload(item.url, {
					filename: "_downloads" + path + file_name
				}, function(d, status) {
					if(status == 200) {
						//setTimeout(function(){
						document.getElementById(item.id).setAttribute(item.attr, plus.io.convertLocalFileSystemURL(d.filename));
						//},300);
					}
				}).start();
			});

		},
		JsonPost: function(params, func) {
			
			var oauth = {
				user_id:common.getLocVal("userId")
			}
			if(typeof params.data === 'undefined') {
				params.data = {};
			}
			mui.extend(true, params.data, oauth);
			console.log(JSON.stringify(params));
			
			$.ajax({
				url: SERVER_NAME + params.url,
				type: "post",
				dataType: "json",
				data: params.data,
				success: function(data){
					if(data.code == 200){
						func(data.data);
					}else{
						func(false);
						common.toast(data.msg);
					}
				},
				error: function(xhr, type, errorThrown) {
					//异常处理；
					console.log(params.url + type);
					
					//common.toast("哎呀~网络不给力~~");
				}
			});
			
		},
		alert: function(title, text, func) {
			mui.alert( text, title, "确定", func, 'div' );
			//plus.nativeUI.alert(text, func, title, "确定",'div');
		},
		confirm: function(title, text, func) {
			
			mui.confirm( text, title, ['确定', '取消'], func, 'div' );
			//plus.nativeUI.confirm(text, func, title, ['确定', '取消']);
		},
		confirms: function(title, text, btns, func) {
			btns = btns || ['确定', '取消'];
			
			mui.confirm( text, title, btns, func, 'div' );
			//plus.nativeUI.confirm(text, func, title, btns);
		},
		toast: function(text) {
			mui.toast(text,'div');
			//plus.nativeUI.toast(text);
		},
		subLastString: function(str) {
			var s = str.substring(0, str.length - 1);
			return s;
		},
		loading: function(title, text) {
			mui.showLoading(title,"div");
			//plus.nativeUI.showWaiting(title);
		},
		closeLoading: function() {
			mui.hideLoading();
			//plus.nativeUI.closeWaiting();
		},
		isEmptyObject: function(obj) {
			//common.alert("提示",JSON.stringify(obj),function(){return false;});
			if(JSON.stringify(obj) === '{}') {
				return true;
			}
			return false;
		},
		isEmptyArray: function(obj) {
			if(JSON.stringify(obj) === '[]') {
				return true;
			}
			return false;
		},
		/**
		 * 回到应用的首页
		 */
		goBackRoot: function() {
			var wvs = plus.webview.all();
			var root = plus.webview.getLaunchWebview();
			for(var i = 0; i < wvs.length; i++) {

				if(wvs[i].getURL() == root.getURL()) {
					root.reload();
					continue;
				}
				wvs[i].close("none");
			}
		},
		isEmpty: function(str) {
			if(str == "" || str == " ") {
				return false;
			} else {
				return true;
			}
		},
		isTelphone: function(mobile) {
			var myreg = /^((13|14|15|17|18)+\d{9})$/;
			if(!myreg.test(mobile)) {
				return false;
			} else {
				return true;
			}
		},
		inArray: function(value, array) {
			var status = false;
			for(var key in array) {
				if(array[key] == value) {
					status = true;
				}
			}
			return status;
		},
		getTimeStamp: function() {
			var timestamp = Date.parse(new Date());
			return timestamp / 1000;
		},
		execScript: function(name, script) {
			var pageObj = plus.webview.getWebviewById(name);
			if(name == 'root') {
				pageObj = plus.webview.getLaunchWebview();
			}
			if(JSON.stringify(pageObj) != 'null') {
				pageObj.evalJS(script);
			}
		},
		closeWin: function(name) {
			var wn = name || plus.webview.currentWebview().id;

			ws = plus.webview.getWebviewById(wn);

			plus.webview.close(ws);
		},
		actionsheet: function(title, btns, func) {
			plus.nativeUI.actionSheet({
				title: title,
				cancel: "取消",
				buttons: btns
			}, func);
		},
		appendByCamera: function(func) {
			plus.camera.getCamera().captureImage(func);
		},
		appendByGallery: function(func) {
			plus.gallery.pick(func);
		},
		appendByGalleryMore: function(num, func) {
			if(!num) {
				num = 9;
			}
			plus.gallery.pick(func, function(e) {}, {
				filter: "image",
				multiple: true,
				maximum: num,
				system: false,
				onmaxed: function() {
					plus.nativeUI.alert('最多只能选择' + num + '张图片');
				}
			});
		},
		upload: function(url, options, imgPath, func) {
			var task = plus.uploader.createUpload(SERVER_NAME + url, options, func);
			task.addFile(imgPath, {
				key: "file"
			});
			if(typeof options == 'object'){
				for(var key in options){
					task.addData(key, options[key]);
				}
			}
			task.addData("user_id", common.getLocVal('userId'));
			task.start();
		},
		checkUpdate: function(type) {
			type = type || '';
			console.log("checkUpdate");
			console.log(UPDATE_JSON + "?v=" + common.getTimeStamp());
			mui.get(UPDATE_JSON + "?v=" + common.getTimeStamp(), {}, function(data) {
				plus.runtime.getProperty(plus.runtime.appid, function(inf) {
					var version = inf.version;
					var sys = plus.os.name;
					//"appid":plus.runtime.appid,"version":plus.runtime.version,"imei":plus.device.imei
					console.log("version:" + version);
					console.log("data:" + JSON.stringify(data));

					var new_v = data[sys].version.split(".");
					var now_v = version.split(".");
					var status = true;
					for(var i = 0; i < 3; i++) {
						if(status) {
							if(parseInt(new_v[i]) > parseInt(now_v[i])) {
								status = false;
							}
						}
					}
					console.log(status);
					if(status) {
						if(type == 'click') {
							common.alert("提示", "已经是最新版本了");
						}
					} else {
						common.confirms("有新版本", data[sys].student_note, ["立即更新", "取　　消"], function(ret) {
							if(ret.index == 0) {
								if(sys == 'iOS') {
									plus.runtime.openURL(data[sys].student_url);
								} else {
									//下载 自动更新
									plus.nativeUI.showWaiting("新版APP下载中,请稍后...");
									var dtask = plus.downloader.createDownload(data[sys].student_url, {
										filename: "_doc/update/"
									}, function(d, status) {
										console.log(JSON.stringify(d));
										if(status == 200) {
											console.log("下载apk成功：" + d.filename);
											//installWgt(d.filename); // 安装wgt包
											plus.runtime.install(d.filename, {}, function() {
												plus.nativeUI.closeWaiting();
												console.log("安装apk文件成功！");
											}, function(e) {
												plus.nativeUI.closeWaiting();
												console.log("安装apk文件失败[" + e.code + "]：" + e.message);
												plus.nativeUI.alert("安装apk文件失败[" + e.code + "]：" + e.message);
											});
										} else {
											console.log("下载apk失败！");
										}
									});
									dtask.addEventListener("statechanged", function(download, state) {
										if(download.state == 3 && state == 200) {
											//plus.nativeUI.toast("新版APK下载中..."+parseInt((download.downloadedSize / download.totalSize) * 100) + "%");
										}

										//console.log(JSON.stringify(download)+","+JSON.stringify(state));
									}, false);

									dtask.start();
								}

							}
						})
					}
				})

			}, 'json');
		},
		installWgt: function(wgtUrl, cbSuccess, cbError) {
			//plus.nativeUI.showWaiting("下载wgt文件...");
			plus.downloader.createDownload(wgtUrl, {
				filename: "_doc/update/"
			}, function(d, status) {
				if(status == 200) {
					console.log("下载wgt成功：" + d.filename);
					//installWgt(d.filename); // 安装wgt包
					plus.runtime.install(d.filename, {}, function() {
						plus.nativeUI.closeWaiting();
						console.log("安装wgt文件成功！");
						cbSuccess();
					}, function(e) {
						plus.nativeUI.closeWaiting();
						console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
						plus.nativeUI.alert("安装wgt文件失败[" + e.code + "]：" + e.message);
					});
				} else {
					console.log("下载wgt失败！");
					cbError();
					//plus.nativeUI.alert("下载wgt失败！");
				}
				//plus.nativeUI.closeWaiting();
			}).start();
		},
		//压缩图片
		compressImage: function(imgPath, savePath, cbSuccess, cbError) {
			plus.zip.compressImage({
				src: imgPath,
				dst: savePath,
				overwrite: false,
				quality: 80
			}, cbSuccess, cbError);
		},
		//图片路径处理
		imageFile: function(url, wid, hei) {
			var width = wid || 100;
			var height = hei || 100;
			return(url + '').replace(/(\w+)\.(\w+)$/g, '$1' + '_' + width + '_' + height + '.$2');
		},
                reload: function () {
                    window.location.reload();
                }
	}
})
